package com.bdqn.service.impl;
import java.util.HashMap;
import	java.util.Map;

import com.bdqn.component.BlogConstants;
import com.bdqn.dao.CommentMapper;
import com.bdqn.entity.Comment;
import com.bdqn.entity.User;
import com.bdqn.service.CommentService;
import com.bdqn.util.Page;
import com.bdqn.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.UUID;

/**
 * @Author SIMBA1949
 * @Date 2020/3/11 23:05
 */
@Service("commentService")
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public Result<Page<Comment>>getPageComments(Integer pageIndex,String uuid) {
        Page<Comment> page ;
        try {
            page = new Page<Comment>(pageIndex,5);
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("uuid",uuid);
            page.setCount(commentMapper.selelctCountByArticleId(param));

            param.put("start",(pageIndex-1)*page.getPageSize());
            param.put("row",page.getPageSize());
            page.setDataList(commentMapper.selelctCountmentListByArticleId(param));
            return Result.createSuccess(page,"加载成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.createError("加载失败");
    }

    @Override
    public Result<Page<Comment>> getPageCommentsBycenterpath(Integer pageIndex, String centerpath) {
        Page<Comment> page ;
        try {
            page = new Page<Comment>(pageIndex,5);
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("centerpath",centerpath);
            page.setCount(commentMapper.selelctCountByArticleId(param));

            param.put("start",(pageIndex-1)*page.getPageSize());
            param.put("row",page.getPageSize());
            page.setDataList(commentMapper.selelctCountmentListByArticleId(param));
            return Result.createSuccess(page,"加载成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.createError("加载失败");
    }

    @Override
    public Result addCommand(Comment comment, HttpSession session) {
       User user =  (User)session.getAttribute(BlogConstants.LOGIN_SESSION_KEY);
       if (user == null) {
           return Result.createError("你还没登录请登录后再试");
       }
        comment.setUuid(UUID.randomUUID().toString().replace("-","").toUpperCase());
        comment.setUserid(user.getUuid());
        comment.setCreatetime(new Date());
       if (commentMapper.insert(comment)>0) {
         return  Result.createSuccess("留言成功");
       }
        return Result.createError("留言失败");
    }
}
